<template>
    <div class="profile">
        <h1>个人信息</h1>
        <form @submit.prevent="saveProfile" class="profile-form">
            <div class="form-item">
                <label>头像：</label>
                <input type="file" @change="handleAvatarChange" class="file-input" />
                <img :src="avatarPreview" alt="头像预览" class="avatar-preview" v-if="avatarPreview" />
            </div>
            <div class="form-item">
                <label>昵称：</label>
                <input v-model="profile.nickname" class="input-field" />
            </div>
            <div class="form-item">
                <label>电话：</label>
                <input v-model="profile.phone" class="input-field" />
            </div>
            <div class="form-item">
                <label>性别：</label>
                <select v-model="profile.gender" class="select-field">
                    <option value="male">男</option>
                    <option value="female">女</option>
                </select>
            </div>
            <div class="form-item">
                <label>密码：</label>
                <input type="password" v-model="profile.password" class="input-field" />
            </div>
            <div class="form-item">
                <label>邮箱：</label>
                <input v-model="profile.email" class="input-field" />
            </div>
            <button type="submit" class="submit-button">保存</button>
        </form>
    </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue';
import axios from 'axios';

interface Profile {
    nickname: string;
    phone: string;
    gender: string;
    password: string;
    email: string;
}

export default defineComponent({
    name: 'Profile',
    setup() {
        const profile = ref<Profile>({
            nickname: '',
            phone: '',
            gender: '',
            password: '',
            email: ''
        });

        const avatarPreview = ref<string>('');

        // 获取当前用户信息
        const fetchUserProfile = async () => {
            try {
                const token = localStorage.getItem('token');
                const userId = localStorage.getItem('userId');
                console.log("用户tk：",token)
                console.log("用户id：",userId)
                const response = await axios.get(`/api/system/user/${userId}`, {
                    headers: {
                        Authorization: `Bearer ${token}`
                    }
                });
                console.log("用户code：",response.data)
                if (response.data.code === 200) {
                    const userData = response.data.data; // 根据后端返回的数据结构调整
                    profile.value = {
                        nickname: userData.nickName || '',
                        phone: userData.phonenumber || '',
                        gender: userData.sex || '',
                        password: '', // 密码通常不返回
                        email: userData.email || ''
                    };
                    avatarPreview.value = userData.avatar || ''; // 假设头像字段为avatar
                } else {
                    console.error('获取用户信息失败:', response.data.msg);
                }
            } catch (error) {
                console.error('获取用户信息失败:', error);
            }
        };


        // 初始化时获取用户信息
        onMounted(() => {
            fetchUserProfile();
        });

        // 处理头像上传
        const handleAvatarChange = async (event: Event) => {
            const target = event.target as HTMLInputElement;
            const file = target.files?.[0];
            if (file) {
                const formData = new FormData();
                formData.append('file', file);

                try {
                    const token = localStorage.getItem('token');
                    const response = await axios.post('/api/system/user/uploadAvatar', formData, {
                        headers: {
                            Authorization: `Bearer ${token}`,
                            'Content-Type': 'multipart/form-data'
                        }
                    });

                    if (response.data.code === 200) {
                        avatarPreview.value = response.data.url; // 假设返回头像URL
                    } else {
                        console.error('头像上传失败:', response.data.msg);
                    }
                } catch (error) {
                    console.error('头像上传失败:', error);
                }
            }
        };


        // 保存个人信息
        const saveProfile = async () => {
            try {
                const token = localStorage.getItem('token');
                const userId = localStorage.getItem('userId'); // 假设用户ID存储在localStorage中
                const userName = localStorage.getItem('userName'); // 用户账号
                const response = await axios.put(
                    '/api/system/user',
                    {
                        userId: userId, // 用户ID
                        userName: userName, // 用户账号
                        nickName: profile.value.nickname, // 昵称
                        phonenumber: profile.value.phone, // 电话
                        sex: profile.value.gender, // 性别
                        email: profile.value.email, // 邮箱
                        avatar: avatarPreview.value // 头像
                    },
                    {
                        headers: {
                            Authorization: `Bearer ${token}`
                        }
                    }
                );

                if (response.data.code === 200) {
                    alert('个人信息保存成功');
                } else {
                    alert('保存失败：' + response.data.msg);
                    console.log("失败信息：",response.data.msg)
                }
            } catch (error) {
                console.error('保存失败:', error);
                alert('保存失败，请稍后重试');
            }
        };


        return {
            profile,
            avatarPreview,
            handleAvatarChange,
            saveProfile
        };
    }
});

</script>


<style scoped lang="scss">
.profile {
    max-width: 600px;
    margin: 0 auto;
    padding: 20px;
    background-color: #f9f9f9;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h1 {
    text-align: center;
    color: #333;
    margin-bottom: 20px;
}

.profile-form {
    display: flex;
    flex-direction: column;
    gap: 15px;
}

.form-item {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

label {
    font-weight: bold;
    color: #555;
}

.input-field,
.select-field {
    padding: 8px;
    border: 1px solid #ddd;
    border-radius: 4px;
    font-size: 14px;
}

.file-input {
    padding: 5px;
}

.avatar-preview {
    margin-top: 10px;
    width: 100px;
    height: 100px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #ddd;
}

.submit-button {
    padding: 10px 15px;
    background-color: #007bff;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-size: 16px;
    transition: background-color 0.3s ease;
}

.submit-button:hover {
    background-color: #0056b3;
}
</style>
